package com.uinnova.product.eam.web.bm.peer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.binary.core.exception.BinaryException;
import com.binary.core.util.BinaryUtils;
import com.binary.framework.exception.ServiceException;
import com.binary.jdbc.Page;
import com.google.common.collect.Lists;
import com.uinnova.product.eam.api.IBmDiagramApiClient;
import com.uinnova.product.eam.api.IFxDiagramApiClient;
import com.uinnova.product.eam.comm.model.es.EamCategory;
import com.uinnova.product.eam.config.Env;
import com.uinnova.product.eam.db.bean.DiagramChangeData;
import com.uinnova.product.eam.model.EamArtifactCiVo;
import com.uinnova.product.eam.model.EamArtifactElementVo;
import com.uinnova.product.eam.model.asset.EamCiRltDTO;
import com.uinnova.product.eam.model.asset.EamReleaseHistoryDTO;
import com.uinnova.product.eam.model.bm.*;
import com.uinnova.product.eam.model.dto.EamHierarchyDto;
import com.uinnova.product.eam.model.enums.ArtifactType;
import com.uinnova.product.eam.model.vo.CheckBatchArtifactRuleVo;
import com.uinnova.product.eam.model.vo.ReleaseModuleDiagramVO;
import com.uinnova.product.eam.service.*;
import com.uinnova.product.eam.service.asset.BmConfigSvc;
import com.uinnova.product.eam.service.bm.QuickDrawingSvc;
import com.uinnova.product.eam.service.handler.PushFacadeService;
import com.uinnova.product.eam.web.bm.bean.ReleaseDiagramReq;
import com.uinnova.product.eam.web.bm.bean.ReleaseModuleDiagramDTO;
import com.uinnova.product.vmdb.comm.model.ci.CCcCiClass;
import com.uinnova.product.vmdb.comm.model.ci.CcCiClass;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiClassInfo;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiInfo;
import com.uinnova.product.vmdb.provider.ci.bean.CiGroupPage;
import com.uinnova.product.vmdb.provider.rlt.bean.CcCiRltInfo;
import com.uinnova.project.api.diagram.v2.client.ESDiagramApiClient;
import com.uinnova.project.base.diagram.comm.diagram.ESDiagramMoveCdt;
import com.uinnova.project.base.diagram.comm.model.ESDiagram;
import com.uinnova.project.base.diagram.comm.model.ESDiagramDTO;
import com.uinnova.project.base.diagram.util.RedisUtil;
import com.uino.bean.cmdb.base.ESCIInfo;
import com.uino.bean.cmdb.base.LibType;
import com.uino.bean.cmdb.query.ESCISearchBean;
import com.uino.dao.cmdb.ESCIClassSvc;
import com.uino.util.sys.SysUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author ch
 * @date 2021/11/3
 */
@Slf4j
@Service
public class BmDiagramPeer {

    private static final String HANDLE_TIP_SET = "HANDLE:TIP:SET:";

    private static final String DIAGRAM_LOCK_KEY = "DIAGRAM:LOCK:KEY:";

    @Resource
    IBmDiagramApiClient bmDiagramApiClient;

    @Resource
    IFxDiagramApiClient fxDiagramApiClient;

    @Resource
    RedisUtil redisUtil;

    @Resource
    EamCategorySvc categorySvc;

    @Resource
    ICISwitchSvc ciSwitchSvc;

    @Resource
    QuickDrawingSvc quickDrawingSvc;

    @Autowired
    ESDiagramApiClient diagramApiClient;

    @Autowired
    IBmHierarchySvc bmHierarchySvc;

    @Autowired
    private IBmHierarchySvc hierarchySvc;

    @Autowired
    private IEamArtifactColumnSvc artifactColumnSvc;

    @Resource
    private IBmMultiModelHierarchySvc modelHierarchySvc;

    @Resource
    private IEamArtifactSvc artifactSvc;

    @Autowired
    private ESCIClassSvc ciClassSvc;

    @Autowired
    private BmConfigSvc bmConfigSvc;

    private static final String IS_APPROVE_KEY = "IS_APPROVE_KEY";

    @Value("${http.resource.space}")
    private String httpResouceUrl;
    @Resource
    private PushFacadeService pushFacadeService;
    private final Random random = new Random();

    public ReleaseValidResponse pushBeforeCheckView(List<CategoryNode> catalogueIds) {
        PushParams params = generateBatchPushParams(catalogueIds);
        if(BinaryUtils.isEmpty(params)){
            return new ReleaseValidResponse();
        }
        return pushFacadeService.checkDiagram(params);
    }

    /**
     * 不再提示
     */
    public boolean cancelTips(String viewType, Long userId) {
        redisUtil.sSet(HANDLE_TIP_SET + viewType, userId);
        return true;
    }

    /**
     * 获取弹出框状态
     */
    public boolean getTipsStatus(String viewType, Long userId) {
        return redisUtil.sHasKey(HANDLE_TIP_SET + viewType, userId);
    }

    public List<EamReleaseHistoryDTO> queryReleaseHistory(String id, Boolean historyFlag) {
        return bmDiagramApiClient.queryReleaseHistory(id, historyFlag);
    }

    public boolean handlerRelease(String diagramId) {
        return bmDiagramApiClient.handlerRelease(diagramId);
    }

    public List<DiagramChangeData> isCheckOScanning(List<String> diagramIds) {
        return fxDiagramApiClient.isCheckOScanning(diagramIds);
    }

    public Map<String, List<DiagramChangeData>> getChangeCIDataByDEnergyId(String diagramId) {
        return fxDiagramApiClient.getChangeCIDataByDEnergyId(diagramId);
    }

    public String publishDiagram(String diagramId, String releaseDesc, Long dirId, String releaseDiagramId) {
        Boolean needApprove = Boolean.FALSE;
        String configType = bmConfigSvc.getConfigType(IS_APPROVE_KEY);
        if (!BinaryUtils.isEmpty(configType) && configType.equalsIgnoreCase("true")) {
            needApprove = Boolean.TRUE;
        }
        return fxDiagramApiClient.publishDiagram(diagramId, releaseDesc, dirId, releaseDiagramId, needApprove);
    }

    public Boolean getVersionChangeCIByDEnergyId(String diagramId) {
        List<DiagramChangeData> data = fxDiagramApiClient.getVersionChangeCIByDEnergyId(diagramId);
        if (CollectionUtils.isEmpty(data)) {
            return false;
        }
        return true;
    }

    public Boolean freshBindingEleByDEnergyId(String diagramId, List<String> names, String releaseDiagramId, List<String> diagramIds) {
        if (BinaryUtils.isEmpty(diagramId) && BinaryUtils.isEmpty(releaseDiagramId) && BinaryUtils.isEmpty(diagramIds)) {
            throw new BinaryException("本地视图ID或发布视图ID不能为空!");
        }
        Integer actionType = Env.GENERAL_DIAGRAM_PUBLISH;
        if (BinaryUtils.isEmpty(diagramId) && BinaryUtils.isEmpty(diagramIds)) {
            actionType = Env.GENERAL_DIAGRAM_CHECK_OUT;
        }
        return fxDiagramApiClient.freshBindingEleByDEnergyId(names, actionType);
    }

    public Map<String, Boolean> getVersionChangeDiagramByDEnergyId(List<String> diagramIds) {
        return fxDiagramApiClient.getVersionChangeDiagramByDEnergyId(diagramIds);
    }

    public List<String> categoryEleNumCheck(String diagramId, String viewType) {
        return fxDiagramApiClient.categoryEleNumCheck(diagramId, viewType);
    }

    public List<CheckBatchArtifactRuleVo> categoryEleNumCheckBatch(List<String> diagramIds) {
        return bmDiagramApiClient.categoryEleNumCheckBatch(diagramIds);
    }

    public Integer freshPublishDiagramAttr() {
        return fxDiagramApiClient.freshPublishDiagramAttr();
    }

    /**
     * 保存CI中自动填充，视图中元素的所属上级元素
     *
     * @param ciList  ci对象信息
     */
    @Deprecated
    public void fillCiListAttrBelongUpperElement(List<CcCiInfo> ciList, String diagramId, LibType libType) {
        if (BinaryUtils.isEmpty(diagramId)) {
            return;
        }
        List<CcCiInfo> fillCiList = ciList.stream().filter(ccCiInfo -> ccCiInfo.getAttrs().containsKey(Env.BM_BELONG_ELEMENT) && BinaryUtils.isEmpty(ccCiInfo.getAttrs().get(Env.BM_BELONG_ELEMENT))).collect(Collectors.toList());
        if (BinaryUtils.isEmpty(fillCiList)) {
            return;
        }
        String loginCode = SysUtil.getCurrentUserInfo().getLoginCode();
        String belongCIProValue = getBelongUpperElementValue(diagramId, loginCode, libType);
        if (BinaryUtils.isEmpty(belongCIProValue)) {
            return;
        }
        for (CcCiInfo ciInfo : fillCiList) {
            ciInfo.getAttrs().put(Env.BM_BELONG_ELEMENT, belongCIProValue);
        }
    }

    private String getBelongUpperElementValue(String diagramId, String loginCode, LibType libType) {
        //1.查询视图信息
        EamCategory diagramCategory = categorySvc.selectByDiagramId(diagramId, loginCode, libType);
        if (BinaryUtils.isEmpty(diagramCategory)) {
            log.error("查询视图目录不存在，视图id:" + diagramId);
            return null;
        }
        //2.视图层级配置，选定所属上级元素字段
        Integer dirLvl = diagramCategory.getDirLvl();
        EamHierarchyDto eamHierarchyDto = bmHierarchySvc.queryByLvlAndModelId(dirLvl, diagramCategory.getModelId(), 1L);
        if (BinaryUtils.isEmpty(eamHierarchyDto)) {
            log.error("层级配置不存在，配置等级：" + dirLvl);
            return null;
        }
        String belongCIProName = eamHierarchyDto.getBelongCIProName();
        if (BinaryUtils.isEmpty(belongCIProName) && eamHierarchyDto.getDirLvl() > 0) {
            throw new ServiceException("该视图层级配置中未选择[自动填充属性]");
        }
        //3.获取上级元素字段，填充ci信息
        String assetCode = diagramCategory.getCiCode();
        ESCISearchBean queryBean = new ESCISearchBean();
        queryBean.setCiCodes(Lists.newArrayList(assetCode));
        Page<ESCIInfo> queryPage = ciSwitchSvc.searchESCIByBean(queryBean, libType);
        if (!BinaryUtils.isEmpty(queryPage.getData())) {
            ESCIInfo esciInfo = queryPage.getData().get(0);
            Object belongCIProValue = esciInfo.getAttrs().get(belongCIProName);
            if (!BinaryUtils.isEmpty(belongCIProValue)) {
                return belongCIProValue.toString();
            }
        }
        return null;
    }

    public Map<String, Map<String, String>> extCheckAttrByDiagramIds(List<String> diagramIds) {
        return fxDiagramApiClient.extCheckAttrByDiagramIds(diagramIds, SysUtil.getCurrentUserInfo().getLoginCode());
    }

    public Map<String, List<String>> batchCategoryEleNumCheck(List<String> diagramIds) {
        return fxDiagramApiClient.batchCategoryEleNumCheck(diagramIds);
    }

    public Map<String, String> batchPublishDiagram(ReleaseModuleDiagramDTO diagramDTO) {
        Map<String, Long> puiblishDirSite = diagramDTO.getPuiblishDirSite();
        return fxDiagramApiClient.batchPublishDiagram(new ArrayList<>(puiblishDirSite.keySet()), puiblishDirSite);
    }

    public Boolean refreshPrepareDiagramId() {
        return fxDiagramApiClient.refreshPrepareDiagramId();
    }

    public Map<String, ESDiagramMoveCdt> checkSpikPage(Map<String, Long> data) {
        return fxDiagramApiClient.checkSpikPage(data);
    }


    public PushParams generateBatchPushParams(List<CategoryNode> catalogueIds) {
        String ownerCode = catalogueIds.get(0).getOwnerCode();
        Long modelId = catalogueIds.get(0).getModelId();
        if(catalogueIds.get(0).getId().equals(0L)){
            return null;
        }
//        List<Integer> dirType = Collections.singletonList(catalogueIds.get(0).getDirType());
        Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
        List<ESDiagram> diagramList;
        if (catalogueIds.size() == 1 && !BinaryUtils.isEmpty(catalogueIds.get(0).getOneView()) && 1 == catalogueIds.get(0).getOneView()) {
            if(BinaryUtils.isEmpty(modelId) && !BinaryUtils.isEmpty(catalogueIds.get(0).getDiagramId())){
                modelId = categorySvc.getModelIdByDiagramIds(Collections.singletonList(catalogueIds.get(0).getDiagramId()), LibType.PRIVATE);
            }
            List<String> diagramIds = Collections.singletonList(catalogueIds.get(0).getDiagramId());
            diagramList = diagramApiClient.selectByIds(diagramIds, null, Collections.singletonList(0));
        } else {
            List<Long> dirIds = catalogueIds.stream().map(CategoryNode::getId).distinct().collect(Collectors.toList());
            //根据目录查询目录下视图信息集合
            diagramList = diagramApiClient.selectByDirIds(dirIds, null, ownerCode, Collections.singletonList(0));
        }
        if (BinaryUtils.isEmpty(diagramList)) {
            throw new ServiceException("当前目录下视图为空");
        }
        List<String> diagramIds = diagramList.stream().map(ESDiagram::getDEnergy).collect(Collectors.toList());
        PushParams params = new PushParams().setOwnerCode(ownerCode);
        params.setModelId(modelId);
        params.setDiagramIds(diagramIds);
        params.setDiagramList(diagramList);
        return params;
    }

    private void findContainDirIds(CategoryNode catalogueId, Set<Long> dirIds) {
        Long id = catalogueId.getId();
        dirIds.add(id);
        if (CollectionUtils.isEmpty(catalogueId.getChildren())) {
            return;
        }
        List<CategoryNode> children = catalogueId.getChildren();
        for (CategoryNode child : children) {
            findContainDirIds(child, dirIds);
        }
    }

    public List<CcCiRltInfo> getActivityListByTaskRlt(String diagramId, String ciCode, String libType) {
        return bmDiagramApiClient.getActivityListByTaskRlt(diagramId, ciCode, libType);
    }

    public CiGroupPage queryCiInfoModuleBySearchBean(ESCISearchBean bean, LibType libType) {
        bean.setDiagramId(null);
        ESCISearchBean designBean = new ESCISearchBean();
        designBean.setPageNum(1);
        designBean.setPageSize(3000);
        designBean.setClassIds(bean.getClassIds());
        designBean.setWords(bean.getWords());
        CiGroupPage designCiPage = ciSwitchSvc.queryPageBySearchBean(designBean, false, LibType.DESIGN);
        List<CcCiInfo> designCiList = designCiPage.getData();
        if (CollectionUtils.isEmpty(designCiList)) {
            return designCiPage;
        }
        List<String> filterPrimaryKeys = designCiList.stream().map(ccCiInfo -> ccCiInfo.getCi().getCiPrimaryKey()).collect(Collectors.toList());
        bean.setCiPrimaryKeys(filterPrimaryKeys);
        CiGroupPage result = ciSwitchSvc.queryPageBySearchBean(bean, false, libType);
        if (result.getTotalCiCount() == 0 && !BinaryUtils.isEmpty(bean.getWords())) {
            bean.setWords(Collections.emptyList());
            result = ciSwitchSvc.queryPageBySearchBean(bean, false, libType);
        }
        return result;
    }

    public Map<String, Object> existCheckData(String diagramId, Long dirId) {
        return fxDiagramApiClient.existCheckData(diagramId, dirId);
    }

    public String generalCheckOutDiagram(String diagramId, Long dirId, Integer actionType, String diagramName) {
        return fxDiagramApiClient.generalCheckOutDiagram(diagramId, dirId, actionType, diagramName);
    }

    public List<DiagramChangeData> existCheckConflict(String diagramId) {
        return fxDiagramApiClient.existCheckConflict(diagramId);
    }

    public List<EamClassDesc> queryClassDesc(Long id) {
        List<EamArtifactElementVo> artifactList = artifactColumnSvc.queryByArtifactId(id, Collections.singletonList(ArtifactType.ASSET_TYPE.val()));
        Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
        List<EamClassDesc> result = new ArrayList<>();
        if(!BinaryUtils.isEmpty(artifactList)){
            List<String> ciElements = artifactList.stream().map(EamArtifactElementVo::getElements).flatMap(Collection::stream).collect(Collectors.toList());
            List<EamArtifactCiVo> ciVoList = ciElements.stream().map(s -> JSON.parseObject(s, EamArtifactCiVo.class)).collect(Collectors.toList());
            List<Long> classIds = ciVoList.stream().filter(each -> "class".equals(each.getType())).map(s-> Long.parseLong(s.getId())).distinct().collect(Collectors.toList());
            if(!BinaryUtils.isEmpty(classIds)){
                CCcCiClass cdt = new CCcCiClass();
                cdt.setIds(classIds.toArray(new Long[]{}));
                cdt.setDomainId(domainId);
                List<CcCiClassInfo> classInfos = ciClassSvc.queryClassByCdt(cdt);
                for (CcCiClassInfo classInfo : classInfos) {
                    CcCiClass ciClass = classInfo.getCiClass();
                    EamClassDesc classDesc = new EamClassDesc();
                    classDesc.setClassId(String.valueOf(ciClass.getId()));
                    classDesc.setClassName(ciClass.getClassName());
                    String desc = BinaryUtils.isEmpty(ciClass.getClassDesc())?"":ciClass.getClassDesc();
                    classDesc.setDesc(desc);
                    String icon = ciClass.getIcon();
                    if (icon != null && !icon.startsWith(httpResouceUrl)) {
                        icon = httpResouceUrl + icon;
                    }
                    classDesc.setIcon(icon);
                    result.add(classDesc);
                }
            }
        }
        return result;
    }


    /**
     * 根据视图ID和版本号查询设计库视图信息 ---- 支持批量
     *
     * @param diagramDTOS
     */
    public Map<String, ESDiagramDTO> queryDiagramInfoByIdAndVersion(List<ReleaseModuleDiagramDTO> diagramDTOS) {
        Map<String, Integer> data = new HashMap<>();
        diagramDTOS.forEach(e -> {
            data.put(e.getDiagramId(), e.getReleaseVersion());
        });
        return fxDiagramApiClient.queryDiagramInfoByIdAndVersion(data);
    }

    /**
     * 根据视图ID校验视图CI版本以及视图本身版本（融合之前的两个接口）
     * @param diagramIds
     * @return
     */
    public Map<String, Boolean> getVersionChangeByDEnergyId(List<String> diagramIds) {
        Map<String, Boolean> data = new HashMap<>();        // 返回值
        // 先校验视图本身版本是否通过校验
        Map<String, Boolean> versionChangeDiagramByDEnergyId = fxDiagramApiClient.getVersionChangeDiagramByDEnergyId(diagramIds);
        List<String> passId = new ArrayList<>();
        for (String diagramId : versionChangeDiagramByDEnergyId.keySet()) {
            if (!versionChangeDiagramByDEnergyId.get(diagramId)) {
                // 通过校验的数据进入下一步校验
                passId.add(diagramId);
            } else {
                // 未通过校验的数据直接插入到返回值中
                data.put(diagramId, true);
            }
        }
        // 再校验视图CI版本是否通过校验
        for (String diagramId : passId) {
            Boolean result = this.getVersionChangeCIByDEnergyId(diagramId);
            data.put(diagramId, result);
        }
        return data;
    }

    /**
     * 自动成图
     */
    public QuickDrawingResp quickDrawing(QuickDrawingDto drawingDto) {
        return quickDrawingSvc.quickDrawing(drawingDto);
    }

    /**
     * 模型完整性校验
     * @param params
     * @return String
     * */

    public String checkModelComplete(ReleaseDiagramReq params) {
        Long modelId = params.getCatalogueIds().get(0).getModelId();
        Integer dirLvl = params.getCatalogueIds().get(0).getDirLvl();
        String ownerCode = params.getCatalogueIds().get(0).getOwnerCode();
        if (BinaryUtils.isEmpty(ownerCode)) {
            ownerCode = SysUtil.getCurrentUserInfo().getLoginCode();
        }

        if (BinaryUtils.isEmpty(modelId) || BinaryUtils.isEmpty(dirLvl)) {
            EamCategory eamDiagramCategory = categorySvc.selectByDiagramId(params.getCatalogueIds().get(0).getDiagramId(), ownerCode, LibType.PRIVATE);
            if (BinaryUtils.isEmpty(eamDiagramCategory) || BinaryUtils.isEmpty(eamDiagramCategory.getModelId())) {
                return null;
            }
            modelId =  eamDiagramCategory.getModelId();
            EamCategory modelRoot = categorySvc.getModelRoot(modelId, ownerCode, LibType.PRIVATE);
            dirLvl = eamDiagramCategory.getDirLvl() - modelRoot.getDirLvl()-1;
        }
        //查询层级配置
        List<EamHierarchyDto> dto = hierarchySvc.queryByModelId(modelId);
        if (BinaryUtils.isEmpty(dto)) {
            throw new BinaryException("未查询到层级配置");
        }
        Map<Integer, EamHierarchyDto> hierarchyMap = dto.stream().collect(Collectors.toMap(EamHierarchyDto::getDirLvl, each -> each, (k1, k2) -> k2));
        EamHierarchyDto hierarchyDto = hierarchyMap.get(dirLvl);
        if (BinaryUtils.isEmpty(hierarchyDto) || !hierarchyDto.getFlag()) {
            return null;
        }
        //开始校验的层级
        List<EamCategory> categories = categorySvc.selectByModelId(modelId, LibType.PRIVATE, ownerCode);
        //私有库-本地的 releaseDiagramCode 都是空的(未发布过的)且大于等于校验层级的
        Integer finalDirLvl = dirLvl;
        List<EamCategory> mustPushCategories = categories.stream().filter(each -> each.getDirLvl()> finalDirLvl).collect(Collectors.toList());
        //取出需要校验的所有层级目录
        Map<Long, CategoryNode> selectNodeMap = params.getCatalogueIds().stream().collect(Collectors.toMap(CategoryNode::getId, each -> each, (k1, k2) -> k2));
        for (EamCategory mustPushCategory : mustPushCategories) {
            CategoryNode categoryNode = selectNodeMap.get(mustPushCategory.getId());
            if(BinaryUtils.isEmpty(categoryNode)){
                return "您当前发布的模型层级不完整，请检查!";
            }
        }
        return null;
    }

    public Map<Integer, Object> checkDiagramConflictByDIds(List<String> diagramIds) {
        return fxDiagramApiClient.checkDiagramConflictByDIds(diagramIds);
    }

    /**
     * 根据业务主键将刷新用户私有库冲突数据刷新为设计库数据
     * @param ciPrimaryKeys
     * @param ownerCode
     * @return
     */
    public Boolean freshConflectData(List<String> ciPrimaryKeys, String ownerCode) {
        return fxDiagramApiClient.freshConflectData(ciPrimaryKeys, ownerCode);
    }

    /**
     *  根据视图历史版本ID查询CI数据
     * @param diagramId
     * @return
     */
    public List<CcCiInfo> getHistroyCIInfoByDiagramId(String diagramId, String sheetId) {
        if (BinaryUtils.isEmpty(diagramId)) {
            return new ArrayList<>();
        }
        return fxDiagramApiClient.getHistroyCIInfoByDiagramId(diagramId, sheetId);
    }

    /**
     *  根据视图历史版本ID查询CI数据-无分类信息
     * @param diagramId
     * @return
     */
    public List<CcCiInfo> getHistroyCIInfoByDiagramIdWithoutCiClass(String diagramId, String sheetId) {
        if (BinaryUtils.isEmpty(diagramId)) {
            return new ArrayList<>();
        }
        return fxDiagramApiClient.getHistroyCIInfoByDiagramIdWithoutCiClass(diagramId, sheetId);
    }

    /**
     *  根据视图历史版本ID查询RLT数据
     * @param diagramId
     * @return
     */
    public List<EamCiRltDTO> getHistroyRltInfoByDiagramId(String diagramId, String sheetId) {
        if (BinaryUtils.isEmpty(diagramId)) {
            return new ArrayList<>();
        }
        return fxDiagramApiClient.getHistroyRltInfoByDiagramId(diagramId, sheetId);
    }

    /**
     *  根据视图历史版本ID查询RLT数据--不包含CI数据
     * @param diagramId
     * @return
     */
    public List<EamCiRltDTO> getHistroyRltInfoByDiagramIdWithoutCI(String diagramId, String sheetId) {
        if (BinaryUtils.isEmpty(diagramId)) {
            return new ArrayList<>();
        }
        return fxDiagramApiClient.getHistroyRltInfoByDiagramIdWithoutCI(diagramId, sheetId);
    }

    public List<CcCiInfo> getRulesByStep(QuickDrawingDto drawingDto) {
        return quickDrawingSvc.getRulesByStep(drawingDto);
    }

    /**
     *  根据视图ID和版本号查询对应的历史版本视图信息 --- 支持批量
     * @param releaseModuleDiagramDTOs
     * @return
     */
    public Map<String,List<EamReleaseHistoryDTO>> queryHistoryDiagramInfoByIds(List<ReleaseModuleDiagramDTO> releaseModuleDiagramDTOs) {
        Map<String, List<Integer>> param = new HashMap<>();
        releaseModuleDiagramDTOs.forEach(e -> {
            param.put(e.getDiagramId(), e.getReleaseVersions());
        });
        return fxDiagramApiClient.queryHistoryDiagramInfoByIds(param);
    }

    public Map<String,List<EamReleaseHistoryDTO>> queryHistoryDiagramByIds(List<ReleaseModuleDiagramVO> releaseModuleDiagramVOs) {
        log.info("################## 初始化的查询参数：【{}】", JSONObject.toJSONString(releaseModuleDiagramVOs));
        Map<String, List<Integer>> param = new HashMap<>();     // 重组传参

        // 查询传参的diagramId中的版本号是否包含最新版本号 如果没有 手动将最新版本号设置进 releaseVersions 集合中
        List<String> diagramIds = releaseModuleDiagramVOs.stream().map(ReleaseModuleDiagramVO::getDiagramId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(diagramIds)) {
            throw new BinaryException("参数异常，视图ID信息不能为空！");
        }
        List<ESDiagram> esDiagrams = diagramApiClient.queryDBDiagramInfoByIds(diagramIds.toArray(new String[0]));
        // 后端过滤未发布的视图数据
        esDiagrams.stream().filter(diagram -> diagram.getIsOpen() == 1).collect(Collectors.toList());
        // log.info("################## 需要查询的视图IDS【{}】", JSONObject.toJSONString(esDiagrams.stream().map(ESDiagram::getDEnergy)));
        for (ESDiagram esDiagram : esDiagrams) {
            for (ReleaseModuleDiagramVO releaseModuleDiagramVO : releaseModuleDiagramVOs) {
                // 判断当前视图ID最新版本号是否包含在传参的数组内 如果没有 手动插入
                if (esDiagram.getDEnergy().equals(releaseModuleDiagramVO.getDiagramId())) {
                    List<Integer> releaseVersions = releaseModuleDiagramVO.getReleaseVersions();        // 参数中的版本号list
                    if (!releaseModuleDiagramVO.getReleaseVersions().contains(esDiagram.getReleaseVersion())) {
                        log.info("################## 视图ID:【{}】,存在最新版本:【{}】，需要添加进参数", releaseModuleDiagramVO.getDiagramId(), esDiagram.getReleaseVersion());
                        releaseVersions.add(esDiagram.getReleaseVersion());
                    }
                    param.put(releaseModuleDiagramVO.getDiagramId(), releaseVersions);
                }
            }
        }
        log.info("################## 最终重组的查询参数：【{}】", JSONObject.toJSONString(param));

        return fxDiagramApiClient.queryHistoryDiagramInfoByIds(param);
    }

    public List<ESDiagram> findDiagramListByDiagramIds(List<String> diagramIds) {
        return diagramApiClient.queryDBDiagramInfoByIds(diagramIds.toArray(new String[0]));
    }
}
